﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using MinecraftLauncher.Model;
using System.Diagnostics;

namespace MinecraftLauncher
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string MC_LOCATION = System.Environment.GetEnvironmentVariable("APPDATA") + "\\.minecraft";

        public MainWindow()
        {
            InitializeComponent();
        }

        public void GetVersions()
        {
            List<MCVersion> versions = new List<MCVersion>();

            foreach (string s in Directory.GetFiles(MC_LOCATION + "\\bin", "minecraft*", SearchOption.TopDirectoryOnly))
            {
                versions.Add(new MCVersion(s));
            }

            fileList.ItemsSource = versions;
        }

        private void testBlock_Loaded(object sender, RoutedEventArgs e)
        {
            this.GetVersions();
        }

        private void launchGame_Click(object sender, RoutedEventArgs e)
        {
            MCVersion ver = (MCVersion)fileList.SelectedItem;
            string minecraftJar = Directory.GetCurrentDirectory() + @"\Assets\Binaries\minecraft.jar";
            
            // TODO: Embed minecraft.jar into application, then when going to launch, write file to the temp dir and run from there.

            string sourceJar = MC_LOCATION + "\\bin\\minecraft.jar";

            string options = "-Xmx1024M -Xms512M -cp {0} net.minecraft.LauncherFrame";

            if (extraOpts.IsChecked.Value)
                options = string.Format(options, minecraftJar);
            else
                options = "-jar " + minecraftJar;

            File.Copy(ver.SourceFile, sourceJar, true);

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo("java", options);
            
            p.Start();
            

            //Environment.Exit(0);
        }

        private void fileList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (fileList.SelectedItem != null)
                launchGame.IsEnabled = true;
            else
                launchGame.IsEnabled = false;
        }
    }
}
